<template>
  <div class="home">
    <div class="header">
      <div class="logo"><i class="iconfont iconnew"></i></div>
      <router-link to="/search" class="search">
        <i class="iconfont iconsearch"></i>
        <span>新闻搜索</span>
      </router-link>
      <span class="user" @click="loginFn">
        <i class="iconfont iconwode"></i>
      </span>
    </div>
    <!-- 2.0 Tab 标签页 -->
    <van-tabs v-model="active" sticky swipeable class="home-tabs">
      <van-tab v-for="item in categoryList" :key="item.id" :title="item.name">
        <!-- 下拉刷新 -->
        <van-pull-refresh v-model="item.isLoading" @refresh="onRefresh">
          <!-- List 列表分页组件 -->
          <van-list
            v-model="item.loading"
            :finished="item.finished"
            @load="onLoad"
            finished-text="没有更多了"
          >
            <MyPost
              v-for="item2 in item.postList"
              :key="item2.id"
              :post="item2"
            ></MyPost>
          </van-list>
        </van-pull-refresh>
        <van-empty v-if="!item.postList.length" description="空空如也" />
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { getCategoryAPI } from "../apis/category";
import { getPostAPI } from "../apis/news";
import { getToken, getCate ,getUserId} from "../utils/localData";
import MyPost from "../components/MyPost";
export default {
  components: {
    MyPost,
  },
  // 申明一些结构数据
  data() {
    return {
      // 默认情况下，都是让头条项高亮
      active: getToken() ? 1 : 0,
      categoryList: getCate(),
      // postList:[],
    };
  },
  // 准备数据和处理
  async created() {
    if (this.categoryList.length === 0) {
      const res = await getCategoryAPI();
      this.categoryList = res.data.data;
      // console.log();
    } else {
      // 本地存储 - 没有关注和头条项目
      // 已登陆 - 添加关注和头条 2项
      // 未登陆 - 添加头条 1 项
      if (getToken()) {
        this.categoryList.unshift(
          { id: 0, name: "关注", is_top: 1 },
          { id: 999, name: "头条", is_top: 1 }
        );
      } else {
        this.categoryList.unshift({ id: 999, name: "头条", is_top: 1 });
      }
    }
    this.categoryList = this.categoryList.map((item) => {
      return {
        ...item,
        postList: [],
        pageIndex: 1,
        pageSize: 2,
        loading: false,
        finished: false,
        isLoading: false,
      };
    });
    // 调用封装后的数据列表函数
    this.getPostListData();
  },
  mounted() {
    // 获取添加伪元素的父级标签
    const tabsDOM = document.querySelector(".van-sticky");
    // 这里必须使用箭头函数，否则后面的使用this会出问题
    tabsDOM.addEventListener("click", (e) => {
      // e.target 触发事件的真实DOM元素
      // console.log('点击了加号',e.target);
      if (e.target.className.indexOf("van-sticky") !== -1) {
        console.log("你点击了加号，跳转到栏目页面");
        this.$router.push({ path: "/classify" });
      } else {
        console.log("点击了栏目");
      }
    });
  },
  methods: {
    loginFn() {
      // 获取用户id
      const id = getUserId()
      if(id) {
        // 跳转
        this.$router.push({path:'/user',query:{id}})
      } else{
        this.$router.push({path:'/login'})
      }
    },
    // 用户下拉
    onRefresh() {
      console.log("onRefresh下拉时触发的函数");
      // 清空所有的新闻
      this.categoryList[this.active].postList = [];
      // 页码重置为1
      this.categoryList[this.active].pageIndex = 1;
      // 隐藏分页组件的加载中的提示
      this.categoryList[this.active].finished = false;

      this.categoryList[this.active].loading = true;
      // 根据新的页码，重新请求数据
      this.getPostListData();
    },
    onLoad() {
      console.log("列表即将滚动到底部");
      this.categoryList[this.active].pageIndex++;
      this.getPostListData();
    },
    async getPostListData() {
      const {
        id: category,
        pageIndex,
        pageSize,
        postList,
      } = this.categoryList[this.active];
      // const activeCateId =  this.categoryList[this.active].id;
      // console.log(activeCateId);
      // 如果返回的数组已经为空（没有更多数据了）
      const res2 = await getPostAPI({
        category,
        pageIndex,
        pageSize,
      });
      if (res2.data.data.length === 0) {
        // 需要
        this.categoryList[this.active].finished = true;
      }
      // 根据栏目id 获取栏目对应的新闻
      // console.log(res2);
      // this.postList = res2.data.data
      // 把栏目对应的新闻放到数组里面
      postList.push(...res2.data.data);
      this.categoryList[this.active].loading = false;
      // 需要主动隐藏加载中的提示
      this.categoryList[this.active].isLoading = false;
    },
  },
  // 监听栏目下标变换
  watch: {
    active() {
      // console.log('active下标变化了',this.active);
      // 如果点开了新的项目，才需要进行栏目的加载
      if (this.categoryList[this.active].postList.length === 0) {
        this.getPostListData();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.home-tabs {
  /deep/ .van-sticky {
    padding-right: 45px;
    &::after {
      content: "+";
      position: absolute;
      right: 0;
      top: 0;
      font-size: 30px;
      height: 45px;
      width: 45px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #fff;
    }
  }
}
.header {
  height: 50px;
  background-color: #ff0000;
  color: #fff;
  display: flex;
  align-items: center;
  .logo {
    width: 70px;
    text-align: center;
    .iconnew {
      font-size: 50px;
    }
  }
  .search {
    flex: 1;
    background-color: rgba(255, 255, 255, 0.5);
    height: 34px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 30px;
    .iconsearch {
      margin-right: 5px;
      margin-top: 5px;
    }
  }
  .user {
    width: 70px;
    text-align: center;
    color: #fff;
    .iconwode {
      font-size: 30px;
    }
  }
}
</style>